// -----------------------------------------------------------------------
//  <copyright file="DeleteResourceCommand.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2025 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2025/1/5 21:45</last-date>
// -----------------------------------------------------------------------

using DaprPlus.Authorization.Domain;
using OSharp.Collections;

namespace DaprPlus.Authorization.Application.Commands;

[AuthConfig(typeof(Resource), ResourceAccessType.RoleLimit, "Delete")]
public class DeleteResourceCommand(long[] ids) : IRequest<ApiResult>, ICommand
{
    public long[] Ids { get; set; } = ids;
}

public class DeleteResourceCommandHandler(IResourceService service) : IRequestHandler<DeleteResourceCommand, ApiResult>
{
    public async Task<ApiResult> Handle(DeleteResourceCommand request, CancellationToken cancellationToken)
    {
        var results = new List<ApiResult>();
        foreach (var id in request.Ids)
        {
            var result = await service.DeleteResourceAsync(id, cancellationToken);
            results.Add(result);
        }

        if (results.All(r => r.IsSuccess()))
        {
            return ApiResult.Success($"资源 {request.Ids.ExpandAndToString()} 删除成功");
        }

        var errors = results.Where(r => !r.IsSuccess()).Select(r => r.Message);
        return ApiResult.Error($"部分资源删除失败：{string.Join(", ", errors)}");
    }
}

public class DeleteResourceCommandValidator : AbstractValidator<DeleteResourceCommand>
{
    public DeleteResourceCommandValidator()
    {
        RuleFor(m => m.Ids)
            .NotEmpty()
            .WithMessage("资源标识符不能为空")
            .Must(ids =>
            {
                return ids.Length == ids.Distinct().Count();
            })
            .WithMessage("批量删除的资源中存在重复的标识符");

        RuleForEach(m => m.Ids)
            .GreaterThan(0)
            .WithMessage("资源标识符无效");
    }
}

